<template>
  <div class="order-page">
    <ShortCut></ShortCut>
    <toubu></toubu>
 
    <div class="container">
      <!-- 检查是否有 userName，如果没有则显示提示信息 -->
      <div v-if="isUserLoggedIn">
        <div class="order-header">
          <h1>我的订单</h1>
          <div class="welcome-message">欢迎回来，{{ userName }}！</div>
        </div>
 
        <!-- 添加搜索框 -->
        <div class="search-box">
          <input type="text" v-model="searchQuery" placeholder="输入订单号进行搜索" @input="searchOrders" class="search-input" />
          <button class="btn btn-primary" @click="searchOrders">搜索</button>
        </div>
 
        <!-- 添加状态标签 -->
        <div class="status-tabs">
          <ul>
            <li v-for="(status, index) in statusOptions" :key="index" @click="filterOrders(status.value)"
              :class="{ active: activeStatus === status.value }">
              {{ status.label }}
            </li>
          </ul>
        </div>
 
        <!-- 显示搜索结果或常规订单列表 -->
        <template v-if="hasSearchResults">
          <h3>搜索结果</h3>
          <!-- 显示分页的搜索结果 -->
          <div class="order-card" v-for="order in paginatedSearchResults" :key="order.orderId || order.id">
            <div class="order-card-header">
              <div class="order-info">
                <span class="order-id">订单号: {{ order.orderNum || order.orderId }}</span>
                <span class="order-date">{{ formatDate(order.orderTIme || order.orderTime) }}</span>
              </div>
              <div class="order-status" :class="getStatusClass(order.Logistics_status || order.status)">
                {{ getStatusText(order.Logistics_status || order.status) }}
              </div>
            </div>
 
            <div class="order-items">
              <div class="order-item" v-for="goods in order.goodsList || [order]" :key="goods.goodsId || goods.id">
                <img :src="goods.goodsImg || goods.imgSrc" :alt="goods.goodsName || goods.name" class="item-image">
                <div class="item-details">
                  <h3 class="item-name">{{ goods.goodsName || goods.name }}</h3>
                  <div class="item-specs" v-if="goods.color || goods.size">
                    <span v-if="goods.color">颜色: {{ goods.color }}</span>
                    <span v-if="goods.size">尺码: {{ goods.size }}</span>
                  </div>
                  <div class="item-price">
                    <span class="unit-price">¥{{ parseFloat(goods.price).toFixed(2) }}</span>
                    <span class="quantity">×{{ goods.num }}</span>
                  </div>
                </div>
                <div class="item-total">
                  ¥{{ (parseFloat(goods.price) * goods.num).toFixed(2) }}
                </div>
              </div>
            </div>
 
            <div class="order-footer">
              <div class="order-actions">
                <button class="btn btn-primary" v-if="(order.Logistics_status === 0)"
                  @click="showPayModal(order)">立即支付</button>
                <button class="btn btn-secondary" @click="cancelOrder(order)"
                  v-if="(order.Logistics_status === 0 || order.Logistics_status === 1)">取消订单</button>
                <button class="btn btn-secondary" @click="(order)" v-if="(order.Logistics_status === 2)">查看物流</button>
                <button class="btn btn-secondary" @click="confirmOrder(order)"
                  v-if="(order.Logistics_status === 1 || order.Logistics_status === 2)">确认订单</button>
                <button class="btn btn-secondary" @click="openReviewModal(order)"
                  v-if="(order.Logistics_status === 3)">商品评价</button>
              </div>
              <div class="order-summary">
                <span>共{{ (order.goodsList ? order.goodsList.length : order.num) }}件商品</span>
                <span class="total-amount">合计: ¥{{ parseFloat(order.total || order.totalAmount).toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <!-- 显示分页的常规订单列表 -->
          <div class="order-card" v-for="order in paginatedOrders" :key="order.orderId || order.id">
            <div class="order-card-header">
              <div class="order-info">
                <span class="order-id">订单号: {{ order.orderNum || order.orderId }}</span>
                <span class="order-date">{{ formatDate(order.orderTIme || order.orderTime) }}</span>
              </div>
              <div class="order-status" :class="getStatusClass(order.Logistics_status || order.status)">
                {{ getStatusText(order.Logistics_status || order.status) }}
              </div>
            </div>
 
            <div class="order-items">
              <div class="order-item" v-for="goods in order.goodsList || [order]" :key="goods.goodsId || goods.id">
                <img :src="goods.goodsImg || goods.imgSrc" :alt="goods.goodsName || goods.name" class="item-image">
                <div class="item-details">
                  <h3 class="item-name">{{ goods.goodsName || goods.name }}</h3>
                  <div class="item-specs" v-if="goods.color || goods.size">
                    <span v-if="goods.color">颜色: {{ goods.color }}</span>
                    <span v-if="goods.size">尺码: {{ goods.size }}</span>
                  </div>
                  <div class="item-price">
                    <span class="unit-price">¥{{ parseFloat(goods.price).toFixed(2) }}</span>
                    <span class="quantity">×{{ goods.num }}</span>
                  </div>
                </div>
                <div class="item-total">
                  ¥{{ (parseFloat(goods.price) * goods.num).toFixed(2) }}
                </div>
              </div>
            </div>
 
            <div class="order-footer">
              <div class="order-actions">
                <button class="btn btn-primary" v-if="(order.Logistics_status === 0)"
                  @click="showPayModal(order)">立即支付</button>
                <button class="btn btn-secondary" @click="cancelOrder(order)"
                  v-if="(order.Logistics_status === 0 || order.Logistics_status === 1)">取消订单</button>
                <button class="btn btn-secondary" @click="(order)" v-if="(order.Logistics_status === 2)">查看物流</button>
                <button class="btn btn-secondary" @click="confirmOrder(order)"
                  v-if="(order.Logistics_status === 1 || order.Logistics_status === 2)">确认订单</button>
                <button class="btn btn-secondary" @click="openReviewModal(order)"
                  v-if="(order.Logistics_status === 3)">商品评价</button>
              </div>
              <div class="order-summary">
                <span>共{{ (order.goodsList ? order.goodsList.length : order.num) }}件商品</span>
                <span class="total-amount">合计: ¥{{ parseFloat(order.total || order.totalAmount).toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </template>
 
        <!-- 分页控件 -->
        <div class="pagination" v-if="showPagination">
          <button class="btn btn-secondary" @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <button class="btn btn-secondary" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        </div>
 
        <div class="empty-state" v-if="!hasSearchResults && filteredOrders.length === 0 && !isSearching">
          <p>没有找到对应状态的订单</p>
          <button class="btn btn-primary"><a href="#/home">去逛逛</a></button>
        </div>
      </div>
 
      <div class="login-prompt" v-else>
        <div class="prompt-content">
          <h3>请登录后查看订单</h3>
          <p>登录后可以查看您的订单记录和物流信息</p>
          <button class="btn btn-primary"><a href="#/login">立即登录</a></button>
        </div>
      </div>
    </div>
 
    <!-- 微信支付弹窗 -->
    <div class="wechat-pay-modal" v-if="showWechatPay">
      <div class="pay-modal-content">
        <div class="pay-header">
          <h3>微信支付</h3>
          <span class="close-btn" @click="showWechatPay = false">×</span>
        </div>
        <div class="pay-body">
          <div class="qrcode-container">
            <img src="../assets/images/wx.jpg" alt="微信支付二维码" class="qrcode-img">
          </div>
          <p class="pay-amount">支付金额：¥{{ currentOrder?.total || currentOrder?.totalAmount || 0 }}</p>
          <p class="pay-tip">请使用微信扫一扫完成支付</p>
        </div>
        <div class="pay-footer">
          <button class="pay-success-btn" @click="handlePaySuccess">已完成支付</button>
        </div>
      </div>
    </div>
 
<!-- 评价弹窗 -->
<div class="review-modal-overlay" v-if="showReviewModal" @click.self="closeReviewModal">
  <div class="review-modal">
    <div class="review-header">
      <h3>发表评价</h3>
      <span class="close-btn" @click="closeReviewModal">×</span>
    </div>
    <div class="review-content">
      <!-- 添加商品切换选项卡 -->
      <div class="product-tabs">
        <button 
          v-for="product in currentOrderProducts" 
          :key="product.goodsId || product.id"
          @click="selectProduct(product)"
          :class="{ active: selectedProductId === (product.goodsId || product.id) }">
          {{ product.goodsName || product.name }}
        </button>
      </div>
      
      <div class="product-info" v-if="currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)">
        <img :src="(currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).goodsImg" 
             alt="商品图片" class="product-image">
        <div class="product-details">
          <p>{{ (currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).goodsName }}</p>
          <p v-if="(currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).color || 
                  (currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).size">
            {{ (currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).color }} 
            {{ (currentOrderProducts.find(p => (p.goodsId || p.id) === selectedProductId)).size }}
          </p>
        </div>
      </div>

      <div class="rating-section">
        <h4>商品评分</h4>
        <div class="rating-stars">
          <span v-for="star in 5" :key="star" @click="setRating(star, selectedProductId)"
            :class="{ active: star <= (currentRating[selectedProductId] || 0) }">★</span>
        </div>
      </div>

      <div class="comment-section">
        <h4>评价内容</h4>
        <textarea v-model="reviews[selectedProductId]" placeholder="请输入您的评价内容"></textarea>
      </div>

      <button class="submit-review-btn" @click="submitReview">提交评价</button>
    </div>
  </div>
</div>
</div>
</template>
 
<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import ShortCut from '@/components/common/ShortCut.vue';
import toubu from '@/components/common/toubu.vue';
 
const orders3000 = ref([]);
const orders3001 = ref([]);
const userName = ref(sessionStorage.getItem('userName') || '');
const userId = ref(sessionStorage.getItem('userId') || '');
const isUserLoggedIn = computed(() => userName.value !== '');
const showWechatPay = ref(false);
const currentOrder = ref(null);
const addressList = ref([]);
const defaultAddress = ref(null);
const selectedAddress = ref(null);
const activeStatus = ref(null);
const searchQuery = ref('');
const searchResults = ref([]);
const currentPage = ref(1);
const itemsPerPage = 5;
const isSearching = ref(false);
const showReviewModal = ref(false);
const currentRating = ref({}); // 改为对象存储每个商品的评分
const reviews = ref({}); // 改为对象存储每个商品的评价内容
const selectedProductId = ref(null); // 当前选中的商品ID
 
// 获取当前订单的所有商品
const currentOrderProducts = computed(() => {
  if (!currentOrder.value) return [];
  return currentOrder.value.goodsList || [currentOrder.value];
});
 
// 显示评价弹窗
const openReviewModal = (order) => {
  currentOrder.value = order;
  showReviewModal.value = true;
  
  // 初始化评分和评价内容
  const products = currentOrderProducts.value;
  products.forEach(product => {
    const productId = product.goodsId || product.id;
    if (!currentRating.value[productId]) {
      currentRating.value[productId] = 5;
    }
    if (!reviews.value[productId]) {
      reviews.value[productId] = '';
    }
  });
  
  // 默认选中第一个商品
  if (products.length > 0) {
    selectedProductId.value = products[0].goodsId || products[0].id;
  }
};
 
// 关闭评价弹窗
const closeReviewModal = () => {
  showReviewModal.value = false;
  currentRating.value = {};
  reviews.value = {};
  selectedProductId.value = null;
};
 
// 设置评分
const setRating = (rating, productId) => {
  currentRating.value[productId] = rating;
};
 
// 选择商品
const selectProduct = (product) => {
  selectedProductId.value = product.goodsId || product.id;
};
 
/// 提交评价
const submitReview = async () => {
  if (!currentOrder.value) return;

  try {
    // 检查所有商品评价是否已填写
    const missingReviews = currentOrderProducts.value
      .filter(product => !(reviews.value[(product.goodsId || product.id)]?.trim()))
      .map(product => product.goodsName || product.name);
    
    if (missingReviews.length > 0) {
      alert(`以下商品评价未填写: ${missingReviews.join(', ')}`);
      return;
    }
    
    // 检查评分是否已设置
    const missingRatings = currentOrderProducts.value
      .filter(product => currentRating.value[(product.goodsId || product.id)] === undefined)
      .map(product => product.goodsName || product.name);
    
    if (missingRatings.length > 0) {
      alert(`以下商品评分未设置: ${missingRatings.join(', ')}`);
      return;
    }
    
    // 为每个商品单独提交评价
    for (const product of currentOrderProducts.value) {
      const productId = product.goodsId || product.id;
      const response = await axios.post(
        "http://127.0.0.1:3000/api/comment/addComment",
        {
          goodid: productId,
          userid: userId.value,
          orderid: currentOrder.value.orderId, // 使用orderNum作为orderId
          size: product.size,
          color: product.color,
          content: reviews.value[productId],
          rating: currentRating.value[productId] // 添加评分字段
        }
      );

      if (response.data.status !== 0) {
        throw new Error(response.data.message || `商品${product.goodsName || product.name}评价提交失败`);
      }
    }
    
    alert("所有评价提交成功！");
    closeReviewModal();
    // 可以在这里刷新订单列表或做其他操作
  } catch (error) {
    console.error("提交评价失败:", error);
    alert("提交评价失败: " + (error.response?.data?.message || error.message));
  }
};

// 定义状态选项
const statusOptions = [
  { label: '全部', value: null },
  { label: '待支付', value: 0 },
  { label: '已支付', value: 1 },
  { label: '已发货', value: 2 },
  { label: '已完成', value: 3 },
  { label: '已取消', value: 4 }
];

// 计算属性：是否有搜索结果
const hasSearchResults = computed(() => searchResults.value.length > 0 && isSearching.value);

// 计算属性：是否显示分页
const showPagination = computed(() => {
  if (hasSearchResults.value) {
    return searchResults.value.length > itemsPerPage;
  }
  return filteredOrders.value.length > itemsPerPage;
});

// 计算属性：总页数
const totalPages = computed(() => {
  if (hasSearchResults.value) {
    return Math.ceil(searchResults.value.length / itemsPerPage);
  }
  return Math.ceil(filteredOrders.value.length / itemsPerPage);
});

// 计算属性：分页后的搜索结果
const paginatedSearchResults = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return searchResults.value.slice(start, end);
});

// 计算属性：分页后的常规订单
const paginatedOrders = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return filteredOrders.value.slice(start, end);
});

// 搜索订单
const searchOrders = () => {
  isSearching.value = true;
  currentPage.value = 1; // 搜索时重置到第一页

  if (!searchQuery.value.trim()) {
    searchResults.value = [];
    isSearching.value = false;
    return;
  }

  // 在combinedOrders中搜索
  const allOrders = combinedOrders.value;
  searchResults.value = allOrders.filter(order => {
    const orderNum = order.orderNum || order.orderId || '';
    return orderNum.toString().includes(searchQuery.value.trim());
  });
};

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

// 修改后的combinedOrders计算属性
const combinedOrders = computed(() => {
  // 处理来自3001端口的订单数据
  const processed3001 = orders3001.value
    .filter(order => order.goodsList && order.goodsList.length > 0)
    .map(order => ({
      ...order,
      orderNum: order.id,
      Logistics_status: parseInt(order.status),
      goodsList: order.goodsList || [],
      orderTIme: order.orderTime,
      total: order.total,
      amount: order.amount,
      userId: order.userId // 确保包含userId字段
    }));

  // 处理来自3000端口的订单数据
  const processed3000 = (orders3000.value.data || [])
    .filter(order => order.userId.toString() === userId.value)
    .map(order => {
      // 确保items存在且是数组
      const items = Array.isArray(order.items) ? order.items : [];

      return {
        orderId: order.orderId,
        orderNum: order.orderNum,
        userId: order.userId,
        total: order.total,
        amount: order.amount,
        method: order.method,
        name: order.name,
        phone: order.phone,
        address: order.address,
        Logistics_status: order.Logistics_status,
        orderTIme: order.orderTime,
        state: order.state,
        goodsList: items.map(item => ({
          goodsId: item.goodsId,
          goodsName: item.goodsName,
          goodsImg: item.goodsImg,
          size: item.size,
          color: item.color,
          price: item.price,
          num: item.num
        })),
        status: order.Logistics_status
      };
    });


  // 合并两个列表并按时间排序
  const combined = [...processed3001, ...processed3000]
    .sort((a, b) => new Date(b.orderTIme || b.orderTime) - new Date(a.orderTIme || a.orderTime));
  return combined;
});

// 根据状态过滤订单
const filteredOrders = computed(() => {
  if (!activeStatus.value && activeStatus.value !== 0) {
    return combinedOrders.value;
  }
  return combinedOrders.value.filter(order =>
    (order.Logistics_status || order.status) === activeStatus.value
  );
});

// 过滤订单的方法
const filterOrders = (status) => {
  activeStatus.value = status;
  currentPage.value = 1; // 过滤时重置到第一页
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知日期';
  const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
  return new Date(dateString).toLocaleDateString('zh-CN', options);
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '已支付',
    2: '已发货',
    3: '已完成',
    4: '已取消',
    12: '已发货' // 添加对状态12的支持
  };
  return statusMap[status] || '未知状态';
};

// 获取状态对应的CSS类
const getStatusClass = (status) => {
  const classMap = {
    0: 'pending',
    1: 'paid',
    2: 'shipped',
    3: 'completed',
    4: 'cancelled',
    12: 'shipped' // 添加对状态12的支持
  };
  return classMap[status] || '';
};

// 获取订单列表的函数
const fetchOrderLists = async () => {
  try {
    // 获取3001端口的订单数据
    const response3001 = await axios.get('http://localhost:3001/orderList', {
      params: { userName: userName.value }
    });
    orders3001.value = response3001.data;

    // 获取3000端口的订单数据
    const response3000 = await axios.get('http://localhost:3000/api/order/getAllOrder');

    if (response3000.data.status === 0) {
      orders3000.value = response3000.data;

    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
  }
};

// 获取地址数据
const fetchAddressData = async () => {
  try {
    if (!userId.value) {
      console.error('未找到用户ID');
      return;
    }

    const response = await axios.get(
      `http://127.0.0.1:3000/api/address/getAddress?userId=${userId.value}`
    );

    if (response.data.status === 0) {
      addressList.value = response.data.data;
      // 找出默认地址
      defaultAddress.value = response.data.data.find(addr => addr.is_default === 1) ||
        response.data.data[0]; // 如果没有默认地址，取第一个
    } else {
      console.error('获取地址失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取地址数据失败:', error);
  }
};

// 显示支付弹窗
const showPayModal = (order) => {
  currentOrder.value = order;
  showWechatPay.value = true;

  // 获取地址信息
  if (addressList.value.length === 0) {
    fetchAddressData();
  }

  // 模拟支付成功检测（实际开发中应该使用WebSocket或轮询查询支付状态）
  setTimeout(() => {
    // 实际开发中这里应该是从服务器获取支付状态
    // 这里只是演示，5秒后自动关闭
    if (showWechatPay.value) {
      handlePaySuccess();
    }
  }, 5000);
};

// 处理支付成功
// 处理支付成功
const handlePaySuccess = async () => {
  try {
    if (!currentOrder.value) {
      throw new Error("无效的订单数据");
    }

    // 获取用户ID
    if (!userId.value) {
      throw new Error("未找到用户ID");
    }

    // 获取选中的地址信息
    const address = selectedAddress.value || defaultAddress.value;
    if (!address) {
      throw new Error("未找到收货地址");
    }

    // 准备完整的订单数据
    const orderData = {
      orderNum: currentOrder.value.orderNum || currentOrder.value.id,
      userId: userId.value,
      total: currentOrder.value.total || currentOrder.value.totalAmount,
      amount: currentOrder.value.goodsList.reduce((sum, item) => sum + (item.num || 1), 0),
      method: 1, // 1表示微信支付
      name: address.receiver_name,
      phone: address.receiver_phone,
      address: address.address,
      Logistics_status: 1, // 1表示已支付
      items: currentOrder.value.goodsList.map(item => ({
        goodsId: item.id,
        goodsName: item.name,
        goodsImg: item.imgSrc,
        size: item.size || '',
        color: item.color || '',
        price: item.price,
        num: item.num || 1
      }))
    };

    // 提交订单到新接口
    const response = await axios.post(
      "http://127.0.0.1:3000/api/order/addOrder",
      orderData  // 提交完整的订单对象
    );

    if (response.data.status === 0) {
      showWechatPay.value = false;

      // 删除3001端口对应的订单
      if (currentOrder.value.orderNum) {
        try {
          await axios.delete(`http://localhost:3001/orderList/${currentOrder.value.orderNum}`);
          console.log('Order deleted from 3001 port successfully');
        } catch (error) {
          console.error('Failed to delete order from 3001 port:', error);
        }
      }

      // 更新订单状态
      currentOrder.value.Logistics_status = 1;
      currentOrder.value.status = '已支付';
      alert("支付成功，感谢您的购买！");
      // 刷新订单列表
      await fetchOrderLists();
    } else {
      throw new Error(response.data.message || "提交订单失败");
    }
  } catch (error) {
    console.error("支付处理失败:", error);
    alert("支付处理失败: " + (error.response?.data?.message || error.message));
    showWechatPay.value = false;
  }
};

// 取消订单
const cancelOrder = async (order) => {
  try {
    if (!order) {
      throw new Error("无效的订单数据");
    }

    // 获取订单号，优先使用orderNum，如果没有则使用orderId
    const orderNum = order.orderNum || order.orderId;
    if (!orderNum) {
      throw new Error("无效的订单号");
    }

    // 发送请求更新订单状态为已取消(4)
    const response = await axios.post(
      "http://localhost:3000/api/order/upOrder",
      {
        Logistics_status: 4, // 4表示已取消
        orderNum: orderNum
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    if (response.data.status === 0) {
      alert("订单取消成功！");
      // 刷新订单列表
      await fetchOrderLists();
    } else {
      throw new Error(response.data.message || "取消订单失败");
    }
  } catch (error) {
    console.error("取消订单失败:", error);
    alert("取消订单失败: " + (error.response?.data?.message || error.message));
  }
};


// 确认订单
const confirmOrder = async (order) => {
  try {
    if (!order) {
      throw new Error("无效的订单数据");
    }

    // 获取订单号，优先使用orderNum，如果没有则使用orderId
    const orderNum = order.orderNum || order.orderId;
    if (!orderNum) {
      throw new Error("无效的订单号");
    }

    // 发送请求更新订单状态为已完成(3)
    const response = await axios.post(
      "http://localhost:3000/api/order/upOrder",
      {
        Logistics_status: 3, // 3表示已完成
        orderNum: orderNum
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );
    console.log(orderNum)
    if (response.data.status === 0) {
      alert("订单确认成功！");
      // 刷新订单列表
      await fetchOrderLists();
    } else {
      throw new Error(response.data.message || "确认订单失败");
    }
  } catch (error) {
    console.error("确认订单失败:", error);
    alert("确认订单失败: " + (error.response?.data?.message || error.message));
  }
};




// 组件挂载时获取订单列表和地址数据
onMounted(async () => {
  await fetchOrderLists();
  if (userId.value) {
    await fetchAddressData();
  }
});
</script>


<style scoped>
/* 评价弹窗样式 */
.product-tabs {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.product-tabs button {
  padding: 5px 10px;
  border: 1px solid #ddd;
  background: #f5f5f5;
  cursor: pointer;
  border-radius: 4px;
}

.product-tabs button.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}
  
.review-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.review-modal {
  width: 90%;
  max-width: 500px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.review-header {
  background-color: #f8f8f8;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
}

.review-content {
  padding: 20px;
}

.product-info {
  display: flex;
  margin-bottom: 20px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 5px;
  margin-right: 10px;
}

.rating-section,
.comment-section,
.store-rating {
  margin-bottom: 20px;
}

.rating-stars {
  font-size: 24px;
  color: #ccc;
}

.rating-stars span {
  cursor: pointer;
  margin-right: 5px;
}

.rating-stars span.active {
  color: #ff9800;
}

.comment-section textarea {
  width: 100%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: vertical;
}

.submit-review-btn {
  width: 100%;
  padding: 10px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.submit-review-btn:hover {
  background-color: #e05555;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
  gap: 15px;
}

.pagination span {
  margin: 0 10px;
}

/* 搜索框样式 */
.search-box {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

/* 搜索结果样式 */
.search-results {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.search-results h3 {
  margin-top: 0;
  color: #333;
}

.status-tabs ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  gap: 10px;
}

.status-tabs li {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.status-tabs li:hover {
  background-color: #e0e0e0;
}

.status-tabs li.active {
  background-color: #1890ff;
  color: white;
}

/* 保持你原有的样式 */
.order-page {
  padding-bottom: 40px;
}

/* 微信支付弹窗样式 */
.wechat-pay-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.pay-modal-content {
  background: white;
  border-radius: 8px;
  width: 350px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.pay-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pay-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.qrcode-container {
  text-align: center;
  margin: 20px 0;
}

.qrcode-img {
  width: 200px;
  height: 200px;
  border: 1px solid #eee;
}

.pay-amount {
  text-align: center;
  font-size: 18px;
  color: #f10180;
  font-weight: bold;
  margin: 10px 0;
}

.pay-tip {
  text-align: center;
  color: #666;
  font-size: 14px;
}

.pay-footer {
  text-align: center;
  margin-top: 20px;
}

.pay-success-btn {
  background: #f10180;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.pay-success-btn:hover {
  background: #e00070;
}

/* 保持你原有的其他样式 */
.order-card {
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 15px;
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.order-info {
  display: flex;
  flex-direction: column;
}

.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 15px;
}

.item-details {
  flex: 1;
}

.item-specs {
  margin: 5px 0;
  color: #666;
  font-size: 13px;
}

.item-specs span {
  margin-right: 10px;
}

.item-price {
  margin: 5px 0;
}

.unit-price {
  font-weight: bold;
  color: #f10180;
}

.quantity {
  margin-left: 10px;
  color: #666;
}

.item-total {
  width: 100px;
  text-align: right;
  font-weight: bold;
  color: #f10180;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.order-actions .btn {
  margin-left: 10px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #f10180;
  color: white;
  border: none;
}

.btn-secondary {
  background-color: white;
  color: #666;
  border: 1px solid #ddd;
}

.order-summary {
  text-align: right;
}

.total-amount {
  font-weight: bold;
  color: #f10180;
  font-size: 18px;
  margin-left: 10px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-state p {
  color: #666;
  margin-bottom: 20px;
}



/* 添加你的样式 */
.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.order-status.pending {
  background-color: #ffc107;
  color: #333;
}

.order-status.paid {
  background-color: #17a2b8;
  color: white;
}

.order-status.shipped {
  background-color: #28a745;
  color: white;
}

.order-status.completed {
  background-color: #28a745;
  color: white;
}

.order-status.cancelled {
  background-color: #dc3545;
  color: white;
}

.order-status.unknown {
  background-color: #6c757d;
  color: white;
}



.order-page {
  background-color: #ffffff;
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.order-header h1 {
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.welcome-message {
  color: #666;
  font-size: 14px;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  overflow: hidden;
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.order-info {
  display: flex;
  align-items: center;
}

.order-id {
  font-weight: 500;
  color: #333;
  margin-right: 15px;
}

.order-date {
  color: #999;
  font-size: 13px;
}

.order-status {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.order-status.pending {
  background-color: #fff8e6;
  color: #fa8c16;
}

.order-items {
  padding: 0 20px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.item-price {
  display: flex;
  align-items: center;
}

.unit-price {
  color: #666;
  font-size: 14px;
}

.quantity {
  color: #999;
  font-size: 13px;
  margin-left: 10px;
}

.item-total {
  width: 100px;
  text-align: right;
  font-weight: 500;
  color: #333;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  border: none;
  outline: none;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #1890ff;
  color: #fff;
}

.btn-primary:hover {
  background-color: #40a9ff;
}

.btn-secondary {
  background-color: #fff;
  color: #666;
  border: 1px solid #d9d9d9;
}

.btn-secondary:hover {
  color: #1890ff;
  border-color: #1890ff;
}

.order-summary {
  display: flex;
  align-items: center;
}

.order-summary span {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.total-amount {
  font-weight: 500;
  color: #f56c6c !important;
  font-size: 16px !important;
}

.empty-state,
.login-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  text-align: center;
}

.empty-state img,
.login-prompt img {
  width: 200px;
  margin-bottom: 20px;
}

.empty-state p,
.login-prompt p {
  color: #999;
  margin: 10px 0 20px;
}

.login-prompt {
  background-color: #fff;
  border-radius: 8px;
  padding: 40px;
}

.login-prompt h3 {
  color: #333;
  font-size: 18px;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .order-card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .order-status {
    margin-top: 10px;
  }

  .order-item {
    flex-wrap: wrap;
  }

  .item-total {
    width: 100%;
    text-align: left;
    margin-top: 10px;
    padding-left: 95px;
  }

  .order-footer {
    flex-direction: column-reverse;
    align-items: flex-end;
    gap: 15px;
  }

  .order-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>